package han.chensing.latos.sound;

import android.content.Context;
import android.content.pm.PackageManager;
import android.media.AudioManager;

import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.badlogic.gdx.backends.android.AndroidMusic;
import com.badlogic.gdx.backends.android.DefaultAndroidAudio;
import com.badlogic.gdx.files.FileHandle;

import han.chensing.latos.AndroidV;

public class CirnoAudio extends DefaultAndroidAudio {

    static int cacheNum=0;

    static {
        System.loadLibrary("cirno-icy");
    }

    public CirnoAudio(Context context, AndroidApplicationConfiguration config) {
        super(context, config);
        AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        String sampleRate = am.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE);
        String framesPerBuffer = am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER);
        AndroidV.supportLowLatency=
                context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUDIO_LOW_LATENCY);
        int framesPerBufferInt=192;
        int sampleRateInt=44100;
        try{
            sampleRateInt=Integer.parseInt(sampleRate);
            AndroidV.sampleRate=sampleRateInt;
        }catch (Exception ignore){}
        try{
            framesPerBufferInt=Integer.parseInt(framesPerBuffer);
            AndroidV.framesPerBuffer=framesPerBufferInt;
        }catch (Exception ignore){}
        init(3,framesPerBufferInt,sampleRateInt);
    }

    private native void init(int capacity,int framesPerBuffer,int sampleRate);

    private native void disposeNative();

    @Override
    public void notifyMusicDisposed(AndroidMusic music) {

    }
    @Override
    public Sound newSound(FileHandle fileHandle) {
        return new CirnoSound(fileHandle,cacheNum++);
    }

    @Override
    public void dispose() {
        super.dispose();
        disposeNative();
    }
}
